<template>
  <el-dialog :visible.sync="dialogVisible" :close-on-click-modal="false" :append-to-body="true" title="选择接收人">
    <div class="dialog-main-tree">
      <el-tree
        ref="treeForm"
        :data="treeData"
        :default-checked-keys="checkedKeys"
        :check-strictly="false"
        :props="defaultProps"
        node-key="id"
        @check="handleCheckChange"
        highlight-current
        accordion
        show-checkbox
        :default-expand-all="false"
      />
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" size="small" @click="SelectuserOK()">确定选择</el-button>
      <el-button type="default" size="small" @click="cancal()">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getDeptAndUsers } from "../api/message";
export default {
  name: "SelectUsers",
  data () {
    return {
      dialogVisible: false,
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'label',
        username: "username",
        btx: '',
        id: 'id'
      },
      checkedKeys: [],
      test: "",
    }
  },
  created () {
    this.getDeptAndUser();
  },
  methods: {
    show () {
      this.dialogVisible = true;
    },
    cancal () {
      this.dialogVisible = false;
    },
    getDeptAndUser () {
      var tath = this;
      tath.treeData = [];
      getDeptAndUsers().then(res => {
        var k = res.data.data;
        for (var i = 0; i < k.length; i++) {
          var datas = {}
          datas.id = 100 + i;
          datas.deptid = k[i].sysDept.deptId;
          datas.label = k[i].sysDept.name;
          datas.username = k[i].sysDept.username;
          datas.children = [];
          datas.btx = 1;
          for (var j = 0; j < k[i].sysUsers.length; j++) {
            var gs = {};
            gs.id = 1000 + j;
            gs.userid = k[i].sysUsers[j].userId;
            gs.label = k[i].sysUsers[j].realName;
            gs.username = k[i].sysUsers[j].username;
            gs.btx = 2;
            datas.children.push(gs)
          }
          tath.treeData.push(datas);
        }
      })
    },

    handleCheckChange (data, checked) {
      this.checkedKeys = [];
      this.test = "";
      for (var i = 0; i < checked.checkedNodes.length; i++) {
        if (checked.checkedNodes[i].btx === 2) {
          this.checkedKeys.push(checked.checkedNodes[i].userid)
          if (i === checked.checkedNodes.length - 1) {
            this.test += checked.checkedNodes[i].label
          }
          else {
            this.test += checked.checkedNodes[i].label + "、"
          }
        }
      }

    },
    SelectuserOK () {
      var key = {
        list: this.checkedKeys,
        keys: this.test,
      };
      this.$emit('CheckedKeys', key);
      this.cancal();
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-main-tree {
  max-height: 400px;
  overflow-y: auto;
}
</style>
